﻿using Assets.Scripts.Bvh.Common;
using System.Collections.Generic;
using UnityEngine;

namespace Assets.Scripts.Bvh.Cpu
{
    public class TrianglesTracker
    {
        // 用于存储所有Mesh三角形的全局坐标信息
        public static List<Triangle> sceneTriangles = new List<Triangle>();
        // 用于存储所有三角形AABB
        public static List<AABB> sceneTrianglesAABBs = new List<AABB>();
        // 三角形个数
        public static int trianglesCount = 0;
        // 最大的包围盒
        public static AABB sceneAABB = AABB.Invalid;

        // 存储带有MeshFilter组件的游戏对象列表
        public static List<GameObject> meshObjects = new List<GameObject>();

        // 更新所有Mesh三角形的全局坐标信息
        public static void UpdateSceneTriangles()
        {
            sceneTriangles.Clear();
            sceneTrianglesAABBs.Clear();
            trianglesCount = 0;
            sceneAABB = AABB.Invalid;
            meshObjects.Clear();

            Triangle tri = Triangle.Invalid;
            AABB triAABB = AABB.Invalid;

            MeshFilter[] meshFilters = GameObject.FindObjectsOfType<MeshFilter>();
            int trisCount = 0;
            foreach (MeshFilter mf in meshFilters)
            {
                Mesh mesh = mf.sharedMesh;
                if (mesh != null)
                {
                    // 获取Mesh的三角形索引数组
                    int[] triangles = mesh.triangles;
                    Vector3[] vertices = mesh.vertices;
                    Matrix4x4 transformMatrix = mf.transform.localToWorldMatrix;

                    // 合并这个mesh的包围盒
                    var meshBoundWorldMin = transformMatrix.MultiplyPoint(mesh.bounds.min);
                    var meshBoundWorldMax = transformMatrix.MultiplyPoint(mesh.bounds.max);
                    sceneAABB = sceneAABB.Union(meshBoundWorldMin, meshBoundWorldMax);

                    // 将每个三角形的顶点转换为全局坐标并存储
                    for (int i = 0; i < triangles.Length; i += 3)
                    {
                        Vector3 globalVertex0 = transformMatrix.MultiplyPoint(vertices[triangles[i]]);
                        Vector3 globalVertex1 = transformMatrix.MultiplyPoint(vertices[triangles[i + 1]]);
                        Vector3 globalVertex2 = transformMatrix.MultiplyPoint(vertices[triangles[i + 2]]);

                        tri.v0 = globalVertex0;
                        tri.v1 = globalVertex1;
                        tri.v2 = globalVertex2;
                        sceneTriangles.Add(tri);
                        trisCount++;

                        triAABB = AABB.CalFromTriangle(tri);
                        sceneTrianglesAABBs.Add(triAABB);
                    }

                    // 将带有MeshFilter的游戏对象添加到列表
                    meshObjects.Add(mf.gameObject);
                }
            }
            trianglesCount = trisCount;
        }
    }
}

